<template>
  <!-- 空运列表 -->
  <customContainer ref="mainConfig" :config="config" />
  <div>
    <el-dialog
      v-model="open2"
      :before-close="cancle2"
      width="30%"
      :title="title2"
    >
      <el-form
        ref="queryForm"
        :inline="true"
        :model="form3"
        label-width="110px"
      >
        <el-form-item
          label="操作时间"
          prop="operationTime"
          :rules="{
            required: true,
            message: '请输入操作时间',
            trigger: 'blur',
          }"
        >
          <el-date-picker
            v-model="form3.operationTime"
            value-format="YYYY-MM-DD"
            type="date"
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
    
        <div class="dialog-footer">
          <el-button @click="cancle2">取 消</el-button>
          <el-button type="primary" @click="sumit2">确 定</el-button>
        </div>
      </el-form>
    </el-dialog>
    <el-dialog        
      v-model="open3"
      :close-on-click-modal="false"
      :title="title3"
      width="90%"
    >
      <el-form
        ref="carbinForm"
        :model="forms"
        inline
        label-width="160px"
        :rules="rule"
      >
        <el-row>
          <el-form-item label="运输类型" prop="shippingType">
            <el-select
              v-model="forms.shippingType"
              filterable
              placeholder="请选择运输类型"
              clearable
              @change="changes"
            >
              <el-option label="空运" selected value="0"></el-option>
              <el-option label="海运" value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-divider></el-divider>
        <el-row>
          <el-form-item label="起运港" prop="portOfDeparture">
            <el-input v-model="forms.portOfDeparture" clearable style="width: 200px;"></el-input>
          </el-form-item>
         
          <el-form-item label="目的港" prop="portOfDestination">
            <el-input v-model="forms.portOfDestination" clearable style="width: 200px;"></el-input>
          </el-form-item>
         
          <el-form-item label="卸货港" prop="portOfDischarge">
            <el-input v-model="forms.portOfDischarge" clearable style="width: 200px;"></el-input>
          </el-form-item>
         
          <el-form-item label="中转港代码" prop="transitPortCode">
            <el-input v-model="forms.transitPortCode" clearable style="width: 200px;"></el-input>
          </el-form-item>
         
          <el-form-item label="主单号" prop="masterOrderNo" class="flex-center">
            <el-input v-model="forms.masterOrderNo" clearable style="width: 200px;"></el-input>
          </el-form-item>
         
          <el-form-item label="分单号" prop="subOrderNo" class="flex-center">
            <el-input v-model="forms.subOrderNo" clearable style="width: 200px;"></el-input>
          </el-form-item>
        
          <el-form-item label="航班/航次" prop="flightNumber" class="flex-center">
            <el-input v-model="forms.flightNumber" clearable style="width: 200px;"></el-input>
          </el-form-item>
         
          <el-form-item label="ETD" prop="etd">
            <el-input v-model="forms.etd" clearable style="width: 200px;"></el-input>
          </el-form-item>
         
          <el-form-item label="截单时间" prop="cutOffTime">
            <el-date-picker
              v-model="forms.cutOffTime"
              style="width: 200px;"
              type="date"
              placeholder="选择日期时间"
              format="YYYY/MM/DD"
              value-format="YYYY-MM-DD"
            ></el-date-picker>
          </el-form-item>
         
          <el-form-item v-if="types == 1" label="装箱类型" prop="packingType">
            <el-select
              v-model="forms.packingType"
              filterable
              placeholder="请选择"
              style="width: 200px;"
            >
              <el-option label="拼箱" value="1"></el-option>
              <el-option label="整柜" value="2"></el-option>
            </el-select>
          </el-form-item>
         
          <el-form-item v-if="types == 1" label="箱型" prop="cabinetTypeList">
            <el-select v-model="forms.cabinetTypeList" multiple style="width: 200px;">
              <el-option
                v-for="dict in dicts[DictDirection.柜子型号]"
                :key="dict.id"
                :label="dict.cabinetType"
                :value="dict.id"
              ></el-option>
            </el-select>
          </el-form-item>
         
          <el-form-item v-if="types == 1" label="箱量" prop="cabinetNumber">
            <el-input v-model="forms.cabinetNumber" :controls="false" style="width: 200px;"></el-input>
          </el-form-item>
        
          <el-form-item v-if="types == 1" label="柜号" prop="cabinetNo">
            <el-input v-model="forms.cabinetNo" style="width: 200px;"></el-input>
          </el-form-item>
        
          <el-form-item v-if="types == 1" label="船代理" prop="agent">
            <el-input v-model="forms.agent" style="width: 200px;"></el-input>
          </el-form-item>
          
          <el-form-item label="配舱备注" prop="cabinRemarks">
            <el-input v-model="forms.cabinRemarks" clearable style="width: 200px;"></el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="cancel4">取 消</el-button>
        <el-button type="primary" @click="handlerSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <feeName ref="feeRef"></feeName>
    <payName ref="payRef"></payName>
    <uploads ref="uploadRef" @refush="initList"></uploads>
    <edit :id="rowId" ref="editRef"></edit>
  </div>
</template>
<script lang="ts" setup>
import { ref, computed, getCurrentInstance, defineAsyncComponent } from 'vue'
import { ElButton, ElMessageBox, ElMessage, ElDivider } from 'element-plus'
import useDicts, { DictDirection } from '@/store/modules/dicts'
// eslint-disable-next-line max-len
import { getlistOrder, domesticInspection, domesticDomestically, foreignInspection, domesticDeclaration, remove, ladingOut, customsClearance, editOrderStatus, getCustomsClearanceByIdOrLadingNO, cabinAllocation, selectFileList } from '@/api/expressManager/clearance'

const dicts = useDicts()
dicts.setDicts(DictDirection.柜子型号)
dicts.setDicts(DictDirection.运输类型)
const edit = defineAsyncComponent(() => import('./components/edit.vue'))
const feeName = defineAsyncComponent(() => import('./components/feeName.vue'))
const payName = defineAsyncComponent(() => import('./components/payName.vue'))
const uploads = defineAsyncComponent(() => import('./components/uploads.vue'))
const SelfDropdown = defineAsyncComponent(() => import('./components/SelfDropdown.vue'))
const rowId = ref([])
const feeRef = ref(undefined)
const payRef = ref(undefined)
const queryParam = ref({
  pageSize: 10,
  pageNum: 1,
  waybillNo: undefined,
  ladingNo: undefined,
  agent: undefined,
  customerCode: undefined,
  flightNumber: undefined,
  portOfDeparture: undefined,
  portOfDestination: undefined,
  datePicker: undefined,
  airlineCompany: undefined,
  status: undefined,
}) 
const forms = ref({
  portOfDeparture: '',
  portOfDestination: '',
  portOfDischarge: '',
  transitPortCode: '',
  packingType: '3',
  masterOrderNo: '',
  cabinetNumber: '',
  subOrderNo: '',
  flightNumber: '',
  etd: '',
  caseNo: '',
  cutOffTime: '',
  cabinetTypeList: [],
  cabinetNo: '',
  agent: '',
  title: '',
  shippingType: '',
  cabinRemarks: '',
})

const open2 = ref(false)
const title2 = ref(null)
const open3 = ref(false)
const title3 = ref(null)
const rule = {
  transportType: [{ required: true, message: '运输类型不能为空', trigger: ['blur', 'change'] }],
  cabinetTypeList: [{ required: true, message: '箱型不能为空', trigger: ['change'] }],
  cabinetNo: [{ required: true, message: '柜号不能为空', trigger: ['blur', 'change'] }],
  masterOrderNo: [{ required: true, message: '主单号不能为空', trigger: ['blur', 'change'] }],
  packingType: [{ required: true, message: '装箱类型不能为空', trigger: ['blur', 'change'] }],
}
const queryForm = ref(undefined)
const carbinForm = ref(undefined)
const uploadRef = ref(undefined)
const single = ref(true),
  // single2 = ref(true),
  // multiple2 = ref(true),
  multiple = ref(true),
  {
    appContext: {
      config: {
        globalProperties: { $validateForm, $download },
      },
    },
  } = getCurrentInstance()
const mainConfig = ref(null)
const editRef = ref(null)
const form3 = ref({
  operationTime: [],
})
const { proxy } = getCurrentInstance() as any
const types = ref(undefined)
const changes = () => {
  types.value = forms.value.shippingType
}
const handleEdit = () => {
  const id = JSON.parse(JSON.stringify(idss.value))
  editRef.value.title = '修改'
  editRef.value.idss = id
  editRef.value.open = true
  editRef.value.loading = true
  editRef.value.initData(id)
}
const handleAddTotalOrder = () => {
  const status = JSON.parse(JSON.stringify(statuss.value))
  if (status[0] == '4') {
    open2.value = true
    title2.value = '签出'
  } else {
    ElMessage.error('只有已排柜的才能操作')
  }
}
const handleDelete = () => {
  const id = JSON.parse(JSON.stringify(idss.value))
  const status = JSON.parse(JSON.stringify(statuss.value))
  if (status[0] == '4') {
    ElMessageBox.confirm('敏感操作, 是否继续?', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      remove(id).then(res => {
        if (res.code == 200) {
          ElMessage.success('签出成功')
          mainConfig.value.getList()
        } else {
          ElMessage.error(res.msg)
        }
      })
    })
  } else {
    ElMessage.error('只有已排柜的才能操作')
  }
}
// 导出账单
const ExportBillHandler = (row: { [key: string]: any }) => {
  const ladingNo = row.ladingNo
  const customerCode = row.customerCode
  $download('finance/customsClearanceReceivable/airAndSeaExportBill', { ladingNo, customerCode }, `${ customerCode }_${ new Date().getTime() }.xlsx`)
}
// 上传下载文件
const ld = ref(undefined)
const uploadingHandler = (row: { [key: string]: any }) => {
  uploadRef.value.upOpen = true
  uploadRef.value.ladingNo = row.ladingNo
  const ladingNo = row.ladingNo
  console.log(ladingNo)
  proxy.ld = ladingNo
  selectFileList(ladingNo).then(res => {
    uploadRef.value.UploadingData = res.data
  })
}
// 配仓
const handleCabin = () => {
  open3.value = true
  title3.value = '配舱'
  const ids = JSON.parse(JSON.stringify(idss.value))
  const data = {
    id: ids[0],
  }
  getCustomsClearanceByIdOrLadingNO(data).then(res => {
    if (res.code == 200) {
      console.log(res)
      proxy.forms = res.data
    } else {
      ElMessage.error(res.msg)
    }
  })
}
const cancel4 = () => {
  open3.value = false
  proxy.$refs.carbinForm.resetFields()
}
const handlerSubmit = () => {
  $validateForm(carbinForm.value, () => {
    cabinAllocation(forms.value).then(res => {
      if (res.code == 200) {
        ElMessage.success('配舱成功')
        open3.value = false
        mainConfig.value.getList()
      } else {
        ElMessage.error(res.msg)
      }
    })
  })
}
// 国内查验
const handleInspection = () => {
  open2.value = true
  title2.value = '国内查验'
}

// 国内报关
const handleDeclaration = () => {
  open2.value = true
  title2.value = '国内报关'
}
// 国内已放行
const handleDomestically = () => {
  open2.value = true
  title2.value = '国内已放行'
}
// 国外查验
const handleForeignInspection = () => {
  open2.value = true
  title2.value = '国外查验'
}
// 国外清关
const customsClearances = () => {
  open2.value = true
  title2.value = '国外清关'
}
// 国外清关已放行
const handleCustomsClearance = () => {
  open2.value = true
  title2.value = '国外清关已放行'
}
const cancle2 = () => {
  open2.value = false
  proxy.$refs.queryForm.resetFields()
}
const sumit2 = () => {
  const ids = JSON.parse(JSON.stringify(idss.value))
  const loadNo = JSON.parse(JSON.stringify(loadNos.value))
  $validateForm(queryForm.value, () => {
    const data = {
      operationTime: form3.value.operationTime,
      ladingNoList: loadNo,
      idList: ids,
    }
    sentRequest(data).then(res => {
      if (res.code == 200) {
        open2.value = false
        ElMessage.success('操作成功')
        proxy.$refs.queryForm.resetFields()
        mainConfig.value.getList()
      } else {
        ElMessage.error(res.msg)
      }
    })  
  })
}
const sentRequest = async (params) => {
  let Res
  switch (title2.value) {
    case '签出':
      Res = await ladingOut(params)
      break
    case '国内报关':
      Res = await domesticDeclaration(params)
      break
    case '国内查验':
      Res = await domesticInspection(params)
      break
    case '国内已放行':
      Res = await domesticDomestically(params)
      break
      
    case '国外清关':
      Res = await customsClearance(params)
      break
    case '国外查验':
      Res = await foreignInspection(params)
      break
    case '国外清关已放行':
      Res = await editOrderStatus(params)
      break
  }
  return Res
}

const tofee = (row: { [key: string]: any }) => {
  feeRef.value.ladingNos = row.ladingNo
  feeRef.value.idss = row.id
  feeRef.value.caseNos = row.caseNo
  feeRef.value.title = '应收费'
  feeRef.value.open = true
  feeRef.value.getList(row.ladingNo)
}
const toPay = (row: { [key: string]: any }) => {
  payRef.value.ladingNos = row.ladingNo
  payRef.value.idss = row.id
  payRef.value.caseNos = row.caseNo
  payRef.value.title = '应付费'
  payRef.value.open = true
  payRef.value.getList(row.orderNo)
}
const initList = () => {
  const lds = ld.value
  selectFileList(lds).then(res => {
    uploadRef.value.UploadingData = res.data
  })
}
const handleRouterPush = (row: { [key: string]: any }) => {
  const id = row.id
  editRef.value.title = '详情'
  editRef.value.open = true
  editRef.value.loading = true
  editRef.value.idss = row.id
  editRef.value.orderNos = row.orderNo
  rowId.value = id
  editRef.value.initData(id)
}
const idss = ref([])
const loadNos = ref([])
const statuss = ref([])
const auditStatuss = ref([])
// const orderNoLists = ref([])
const caseNos = ref([])
const handleTableSelect = (rows: { [key: string]: any }[]) => {
  console.log(caseNos)
  caseNos.value = rows.map((item) => item.caseNo)
  statuss.value = rows.map((item) => item.status)
  auditStatuss.value = rows.map((item) => item.auditStatus)
  idss.value = rows.map((item) => item.id)
  loadNos.value = rows.map((item) => item.ladingNo)
  single.value = rows.length != 1
  multiple.value = !rows.length
// orderNoLists.value = rows.map((item) => item.orderNo)
// multiple2.value=!rows.length || rows.some(el => el.status == 6);
// single2.value=rows.some(el => el.transportType == 2);
}
const config = computed({
  get() {
    return {
      query: {
        fields: [
          {
            label: '客户订单号',
            prop: 'waybillNo',
            option: {
              placeholder: '请输入客户订单号',
              type: 'textarea',
            },
          },
          {
            label: '提单号',
            prop: 'ladingNo',
            option: {
              placeholder: '请输入提单号',
              type: 'textarea',
            },
          },
          {
            label: '服务商',
            prop: 'agent',
            option: {
              placeholder: '请输入系统订单号',
              dictInfo: { dict: DictDirection.服务商 },
            },
          },
          {
           
            label: '委托单位',
            prop: 'customerCode',
            option: {
              dictInfo: { dict: DictDirection.客户 },
            },
          },
          {
            label: '航次/航班号',
            prop: 'flightNumber',
            option: {
              placeholder: '请输入航次/航班号',
             
            },
          },
          {
            label: '起运港',
            prop: 'portOfDeparture',
            option: {
              placeholder: '请输入起运港',
             
            },
          },
          {
            label: '目的港',
            prop: 'portOfDestination',
            option: {
              placeholder: '请输入目的港',
             
            },
          },
          
          {
            type: 'date-picker',
            label: '起航时间',
            prop: 'datePicker',
            option: {
              type: 'date',
            },
          },
			
          {
            type: 'select',
            label: '订单状态',
            prop: 'status',
            option: {
              dictInfo: { dict: DictDirection.包裹状态 },
            },
          },
      
        ],
        queryParams: queryParam.value,
        formOption: {},
      },
      btns: [
        {
          title: '配舱',
          type: 'primary',
          onClick: handleCabin,
          disabled: single.value,
        },
        {
          title: '修改',
          type: 'primary',
          onClick: handleEdit,
          disabled: single.value,
        },

        {
          title: '签出',
          type: 'info',
          onClick: handleAddTotalOrder,
          disabled: single.value,
        },

        {
          title: '删除',
          type: 'warning',
          onClick: handleDelete,
          disabled: single.value,
        },
        {
          title: '国内查验',
          type: 'success',
          onClick: handleInspection,
          disabled: multiple.value,
		
        },
        {
          title: '国内报关',
          type: 'danger',
          onClick: handleDeclaration,
          disabled: multiple.value,
        },

        {
          title: '国内已放行',
          type: 'info',
          onClick: handleDomestically,
          disabled: multiple.value,
        },
        {
          title: '国外查验',
          type: 'primary',
          onClick: handleForeignInspection,
          disabled: multiple.value,
        },

        {
          title: '国外清关',
          type: 'primary',
          disabled: multiple.value,
          onClick: customsClearances,
        },
        {
          title: '国外清关已放行',
          type: 'info',
          disabled: multiple.value,
          onClick: handleCustomsClearance,
        },
      ],
      table: {
        columns: [
          { type: 'selection', width: '55', align: 'center' },
          { label: '提单号', width: '125', align: 'center', prop: 'ladingNo' },
          { label: '报价编号', align: 'center', width: '100', prop: 'quotationNo' },
          { label: '委托单位', align: 'center', width: '100', prop: 'customerName' },
          { label: '客户单号', width: '120', align: 'center', prop: 'waybillNo' },
          { label: '贸易条款', align: 'center', prop: 'tradeTerms' },
          { label: '服务类型', width: '100', align: 'center', prop: 'serviceType' },
          { label: '服务商简称', align: 'center', width: '150', prop: 'agent' },
          { label: '服务渠道', align: 'center', width: '150', prop: 'serviceChannelCode' },
          { label: '状态', align: 'center', prop: 'splittingStatus', width: '120' },
          { label: '运输类型',
            align: 'center',
            prop: 'transportType',
            width: '120',
            autoFormatter: {
              dict: DictDirection.运输类型,
              rowKey: 'transportType',
            } },
          { label: '订舱管理', align: 'center', prop: 'bookingManagement', width: '180' },
          { label: '国外代理', align: 'center', width: '100', prop: 'foreignAgent' },
          { label: '航空公司', align: 'center', prop: 'airlineCompany' },
          { label: '货值', align: 'center', prop: 'valueGoods', width: '100' },
          { label: 'classNo号', width: '100', align: 'center', prop: 'classno' },
          { label: '起飞时间', width: '120', align: 'center', prop: 'departureTime' },
          { label: '预计排仓时间', width: '120', align: 'center', prop: 'estimatedArrangementTime' },
          { label: '起运港', align: 'center', prop: 'portOfDeparture' },
          { label: '目的港', align: 'center', width: '120', prop: 'portOfDestination' },
          { label: '卸货港', align: 'center', width: '120', prop: 'portOfDischarge' },
          { label: '中转港代码', align: 'center', prop: 'transitPortCode', width: '120' },
          { label: '主单号', align: 'center', prop: 'masterOrderNo', width: '120' },
          { label: '分单号', align: 'center', prop: 'subOrderNo', width: '120' },
          { label: '航班号', align: 'center', prop: 'flightNumber', width: '120' },
          { label: 'ETD', align: 'center', prop: 'etd', width: '120' },
          { label: '截单时间', align: 'center', prop: 'cutOffTime', width: '120' },
          { label: '发货人', align: 'center', prop: 'consignor', width: '120' },
          { label: '收货人', align: 'center', prop: 'consignee', width: '120' },
          { label: '通知人1', align: 'center', prop: 'notifier1', width: '120' },
          { label: '通知人2', align: 'center', prop: 'notifier2', width: '120' },
          { label: '唛头', align: 'center', prop: 'shippingMark', width: '120' },
          { label: '英文品名', align: 'center', prop: 'englishName', width: '120' },
          { label: '付款方式', align: 'center', prop: 'paymentMethod', width: '120' },
          { label: '运输条款', align: 'center', prop: 'transportClause', width: '120' },
          { label: '提单形式', align: 'center', prop: 'ladingForm', width: '120' },
          { label: '总件数', align: 'center', prop: 'receivingTotal', width: '120' },
          { label: '总实重', align: 'center', prop: 'receivingTotalWeight', width: '120' },
          { label: '总材积重', align: 'center', prop: 'receivingTotalWood', width: '120' },
          { label: '总体积重', align: 'center', prop: 'volumeWeightTotal', width: '120' },
          { label: '总计费重', align: 'center', prop: 'receivingTotalCharging', width: '120' },
          { label: '订舱备注', align: 'center', prop: 'bookingRemarks', width: '120' },
          { label: '配舱备注', align: 'center', prop: 'cabinRemarks', width: '120' },
          { label: '操作备注', align: 'center', prop: 'operationRemarks', width: '120' },
          { label: '创建人', align: 'center', prop: 'createUser', width: '120' },
          { label: '创建时间', align: 'center', prop: 'createDate', width: '120' },
          { label: '业务员', align: 'center', prop: 'salesman', width: '120' },
          { label: '客服员', align: 'center', prop: 'customerServiceStaff', width: '120' },
          {
            label: '操作',
            width: '252px',
            fixed: 'right',
            align: 'center',
            render(h, params) {
              const buttons = [
               
                {
                  label: '查看详情',
                  clickFun: handleRouterPush,
                },
                {
                  label: '导出账单',
                  clickFun: ExportBillHandler,
                },
                {
                  label: '上传下载文件',
                  clickFun: uploadingHandler,
                }]
              return [
                h(
                  ElButton,
                  {
                    text: true,
                    type: 'primary',
                    onClick: () => { tofee(params.row) },
                  },
                  {
                    default: () => '应收费',
                  },
                ),
                h(
                  ElDivider,
                  { direction: 'vertical' },
                ),
                h(
                  ElButton,
                  {
                    text: true,
                    type: 'primary',
                    // icon: el.icon,
                    onClick: () => { toPay(params.row) },
                  },
                  {
                    default: () => '应付费',
                  },
                ),
                h(
                  ElDivider,
                  { direction: 'vertical' },
                ),
                h(
                  SelfDropdown,
                  {
                    items: [
                      ...buttons,
                    ],
                    onHandleCommand(command) {
                      command.clickFun && command.clickFun(params.row)
                    },
                  },
                ),
              ]
            },
          },
        ],
        event: {
          onSelectionChange: (rows) => {
            handleTableSelect(rows)
          },
        },
      },
      api: getlistOrder,
      customKey: 'express/mainBusiness/terminalServices/CustomsClearance',
    }
  },
  set(val) {
    return val
  },
  // customKey: 'express-orderInfo',
})
</script>
<style lang="less" scoped>
/deep/.is-guttered {
  padding: 5px;
}
.dialog-footer {
  text-align: right;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
